import React, { useRef } from 'react';
import { Modal, Form, Input, Select, Row, Col, Divider, Button, InputNumber, Tabs, Radio, Typography, List, Space } from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import type { ApiInfo, ApiMapper, ApiParamInfo } from '../txs/types'; // 假设有类型定义文件
import MonacoEditor from "@/pages/component/MonacoEditor";
import { getObject, toast, requestBody, apis } from "@/service/common";
import type { CheckboxGroupProps } from 'antd/es/checkbox/Group';


interface ApiMapperModalProps {
    visible: boolean;
    onCancel: () => void;
    onOk: (values: Partial<ApiInfo>) => void;
    initialValues?: Partial<ApiInfo>;
    confirmLoading?: boolean;
}

const options: CheckboxGroupProps<string>['options'] = [
    { label: '参数说明', value: 'parameter' },
    { label: '响应结果', value: 'response' },
];


export const LookApiModal: React.FC<ApiMapperModalProps> = ({
    visible,
    onCancel,
    onOk,
    initialValues,
    confirmLoading,
}) => {
    const [form] = Form.useForm();
    const [result, setResult] = React.useState<string>('{}')
    const [requestParams, setRequestParams] = React.useState<string>('{}')
    const [apiInfo, setApiInfo] = React.useState<ApiInfo>()
    const [optSelect, setOptSelect] = React.useState<string>('parameter')

    const getParams = () => {
        getObject({ url: apis.apiServer.params, data: { id: initialValues.id } })
            .then(({ data }) => {
                setRequestParams(JSON.stringify(data, null, 2));
            }).catch(error => {
                setRequestParams(JSON.stringify(error, null, 2));
            });
    }

    const requestApi = () => {
        requestBody({ url: apis.apiServer.browseApi + apiInfo?.path, data: JSON.parse(requestParams) }).then((data) => {
            setResult(JSON.stringify(data, null, 2))
            setOptSelect("response")
        }).catch(error => {
            setResult(JSON.stringify(error, null, 2));
            setOptSelect("response")
        });
    }
    React.useEffect(() => {
        if (visible) {
            setResult("{}")
            setOptSelect("parameter")
            if (initialValues) {
                setApiInfo({ ...initialValues })
                getParams()
            }
        }
    }, [visible]);

    return (
        <Modal
            title="浏览接口"
            visible={visible}
            onCancel={onCancel}
            footer={null}
            width="100%"
            bodyStyle={{ height: '85vh', padding: 0 }}
            style={{ top: 0, padding: 0 }}
            destroyOnClose
            confirmLoading={confirmLoading}
            maskClosable={false}
        >
            <div className='flex h-full' style={{ gap: '16px', padding: '16px' }}>
                <div style={{ width: '100%', overflowY: 'auto', paddingRight: '8px' }}>

                    <div className='flex gap-2 mb-2'>
                        <Input addonBefore="POST" value={apiInfo?.path} defaultValue="mysite" />
                        <Button type="primary" onClick={requestApi}>请求</Button>
                    </div>
                    <MonacoEditor
                        height="90%"
                        width='100%'
                        language="json"
                        onChange={(value: any) => {
                            setRequestParams(value)

                        }}
                        value={requestParams}
                        editorOptions={{ automaticLayout: true }}
                    />
                </div>
                <div style={{ width: '100%', height: '100%' }}>
                    <div className='mb-2'>
                        <Radio.Group
                            block
                            options={options}
                            value={optSelect}
                            onChange={(e) => setOptSelect(e.target.value)}
                            optionType="button"
                            buttonStyle="solid"
                        />
                    </div>
                    {
                        optSelect === "parameter" ?
                            apiInfo?.mappers?.map(m => (
                                <div key={m.code} style={{ marginBottom: 16, padding: 12, border: '1px solid #f0f0f0', borderRadius: 4, background: '#fafafa' }}>
                                    <Typography.Title level={5} style={{ marginBottom: 12 }}>
                                        {m.code} - {m.name}
                                    </Typography.Title>
                                    <List
                                        size="small"
                                        dataSource={m.paramInfos || []}
                                        renderItem={p => (
                                            <List.Item key={p.code} style={{ paddingLeft: 24 }}>
                                                <Space size="middle">
                                                    <Typography.Text code>{p.code}</Typography.Text>
                                                    <Typography.Text>{p.name}</Typography.Text>
                                                    <Typography.Text type="secondary">{p.datatype}</Typography.Text>
                                                </Space>
                                            </List.Item>
                                        )}
                                        locale={{ emptyText: '无参数信息' }}
                                        bordered
                                    />
                                </div>
                            ))
                            :
                            <MonacoEditor
                                height="90%"
                                width='100%'
                                language="json"
                                onChange={(value: any) => {
                                    setResult(value)

                                }}
                                value={result}
                                editorOptions={{ automaticLayout: true }}
                            />
                    }


                </div>
            </div>

        </Modal>
    );
};
